﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
using TCL.EO;
using System.Configuration;

namespace TCL.FUNC
{
    public class Sync
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sUrl_Server">http://10.15.144.28:8080/sync_db/</param>
        /// <param name="sUrl_Client">C:\db\dbfile.txt</param>
        /// <param name="iVersion">format: yyyyMMddHHmmss</param>
        /// <param name="sFileNameExe">CapNhatDanhMucChuan.exe</param>
        /// <returns>Error</returns>
        public String Sync_Category(String sUrl_Server, String sUrl_Client)
        {
            try
            {
                Int64 iVersion = 0;
                String sFileNameExe = Convert.ToString(System.AppDomain.CurrentDomain.FriendlyName).Replace(".vshost", "");
                String sExtension = Path.GetExtension(sUrl_Client);
                if (!sUrl_Client.Contains(":\\") && sUrl_Client.Length > 3)
                {
                    while (sUrl_Client.StartsWith("\\"))
                    {
                        sUrl_Client = sUrl_Client.Substring(1);
                    }
                    //sUrl_Client = System.IO.Directory.GetCurrentDirectory().Replace("\\bin\\Debug", "") + "\\" + sUrl_Client;
                    sUrl_Client = System.IO.Directory.GetCurrentDirectory()  + "\\" + sUrl_Client;
                }

                if (String.IsNullOrEmpty(sUrl_Server))
                    return "Không tìm thấy địa chỉ máy chủ (vd: http://10.15.144.28:8080/sync_db/)";
                else if (String.IsNullOrEmpty(sFileNameExe))
                    return "Không tìm thấy tên chương trình (vd: CapNhatDanhMucChuan.exe)";
                else if (String.IsNullOrEmpty(sExtension))
                    return "Không tìm thấy đuôi file (vd: .sqlite)";
                else if (String.IsNullOrEmpty(sUrl_Client) || !File.Exists(sUrl_Client))
                    return String.Format("Không tìm thấy địa chỉ [{0}] để lưu file (vd: db\\dbfile.sqlite)", sUrl_Client);

                Int64.TryParse(ConfigurationSettings.AppSettings["DB_Version"], out iVersion);

                List<FileInUriEO> lstLink = new List<FileInUriEO>();
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(sUrl_Server);
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                    {
                        string html = reader.ReadToEnd();

                        // 1.
                        // Find all matches in file.
                        Regex regex = new Regex(@"(<a.*?>.*?</a>)", RegexOptions.IgnoreCase);
                        MatchCollection matches = regex.Matches(html);

                        if (matches.Count > 0)
                        {
                            // 2.
                            // Loop over each match.
                            foreach (Match m in matches)
                            {
                                string value = m.Groups[1].Value;
                                FileInUriEO i = new FileInUriEO();

                                // 3.
                                // Get href attribute.
                                String sm = "href=\"(.*?)" + sExtension + "\"";
                                //@"href=\""(.*?).txt\"""
                                Match m2 = Regex.Match(value, sm, RegexOptions.IgnoreCase);
                                if (m2.Success)
                                {
                                    i.sHref = m2.Groups[1].Value;

                                    // 4.
                                    // Remove inner tags from text.
                                    //string t = Regex.Replace(value, @"\s*<.*?>\s*", "", RegexOptions.IgnoreCase);
                                    //i.Text = t;
                                    Int64 iTemp = 0;
                                    Int64.TryParse(Path.GetFileName(i.sHref), out iTemp);
                                    i.iFileName = iTemp;

                                    lstLink.Add(i);
                                }

                            }
                        }
                    }
                }
                if (lstLink.Count > 0)
                {
                    FileInUriEO itemMax = lstLink.OrderByDescending(n => n.iFileName).FirstOrDefault();

                    Int64 iVer = lstLink.Max(t => t.iFileName);
                    if (iVer > iVersion)
                    {
                        WebClient client = new WebClient();
                        client.DownloadFile(sUrl_Server + iVer + sExtension, sUrl_Client);



                        String exePath = Directory.GetCurrentDirectory();
                        exePath = Path.Combine(exePath, sFileNameExe);
                        Configuration config = ConfigurationManager.OpenExeConfiguration(exePath);
                        var setting = config.AppSettings.Settings["DB_Version"];
                        if (setting != null)
                        {
                            setting.Value = Convert.ToString(iVer);
                        }
                        else
                        {
                            config.AppSettings.Settings.Add("DB_Version", Convert.ToString(iVer));
                        }

                        config.Save(ConfigurationSaveMode.Modified);
                        ConfigurationManager.RefreshSection("appSettings");

                    }
                }

                return String.Empty;
            }
            catch (Exception ex)
            {
                return (ex.ToString());
            }
        }
    }
}
